<?php
namespace App\Repository\Db;

use App\Exceptions\ValidateException;
use App\Repository\Contracts\OrderCartInterface;
use App\Repository\Contracts\OrderInterface;
use App\Repository\Contracts\OrderJavaInterface;
use App\Repository\Contracts\SettingInterface;
use Illuminate\Support\Facades\DB;

/**
 * @Author:: HuangYin
 * @DateTime: 2017-01-16 14:58
 *
 * @Description:
 */
class OrderRepository extends Repository implements OrderInterface
{
    protected $rules = [
        'created' => [
            'store_id' => 'required'
        ]
    ];

    protected $messages = [
        'store_id.required' => "门店 ID 不能为空"
    ];

    protected function modelName()
    {
        return 'App\Model\Order';
    }

    public function lists($limit, $page, $map = [])
    {
        $query = $this->searchMap($map);
        $total = $query->count();
        $list = $query->orderBy('id', 'desc')->simplePaginate($limit, ['*'], 'page', $page);

        return $this->simplePaginate('list', $list->items(), $total, ceil($total/$limit), $page);
    }

    public function detail($id)
    {
        $result = [];
        $data = $this->model->where('id', '=', $id)->with('detail')->first();
        if ($data) {
            $result = $data->toArray();
            $result['detail'] = $data->detail->toArray();
        }

        return $result;
    }

    public function created(array $data)
    {
        // 表单验证
        $this->validate($data, 'created');
        try {
            // 开启事物
            DB::beginTransaction();
            $time = time();
            // 读取门店详情
            $setting = $this->container->make(SettingInterface::class)->findByName('storeConfig');
            if ($setting) {
                $storeConfig = json_decode($setting->config, true);
            } else {
                throw new ValidateException('请先完门店善配置信息');
            }
            // 读取订单车所有信息
            $orderCart = $this->container->make(OrderCartInterface::class)->lists($data['store_id']);
            if (!$orderCart) {
                throw new ValidateException('订单车没有商品');
            }
            // 写入订单表
            $orderData = [
                'store_id' => $data['store_id'], 'store_name' => $storeConfig['storeName'],
                'shopkeeper' => $storeConfig['shopkeeper'],  'phone' => $storeConfig['phone'],
                'tel' => $storeConfig['tel'], 'number' => date('YmdHis', $time) . mt_rand(100, 1000),
            ];
            $orderId = $this->save($orderData);
            // 写入订单详情表
            $orderDetail = [];
            foreach ($orderCart as $val) {
                $orderDetail[] = [
                    'order_id' => $orderId, 'goods_id' => $val['goods_id'], 'zh_name' => $val['zh_name'],
                    'en_name' => $val['en_name'], 'price' => $val['price'], 'counts' => $val['counts'],
                    'created_at' => $time, 'updated_at' => $time
                ];
            }
            DB::table('order_detail')->insert($orderDetail);
            // 清空订单车
            $this->container->make(OrderCartInterface::class)->clear();
            // 关闭事务
            DB::commit();
            return $orderId;
        } catch (ValidateException $e) {

            throw new ValidateException($e->getMessage());
        }
    }

    public function purchasing($storeId, $id)
    {
        $data = $this->detail($id);
        if (env('JAVA_NETWORK')) {
            if ($this->container->make(OrderJavaInterface::class)->syncCreated($storeId, $data)) {
                return $this->update(['status' => 2], $id, 'id');
            }
        }

        throw new ValidateException('当前处于离线状态,请稍后');
    }

    public function confirm($id)
    {
        $data = $this->detail($id);
        if (env('JAVA_NETWORK')) {
            if ($this->container->make(OrderJavaInterface::class)->syncUpdated($data['number'])) {
                return $this->update(['status' => 3], $id, 'id');
            }
        }

        throw new ValidateException('当前处于离线状态,请稍后');
    }
}